package com.focusai.efairy.network;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * Created by heqingbao on 2016/7/22.
 */
public class ProgressRequestBody extends RequestBody {

    private RequestBody delegate;
    private ProgressListener progressListener;

    private ProgressSink progressSink;

    public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) {
        this.delegate = delegate;
        this.progressListener = progressListener;
    }

    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }

    @Override
    public long contentLength() throws IOException {
        try {
            return delegate.contentLength();
        } catch (Exception e) {
            return super.contentLength();
        }
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        progressSink = new ProgressSink(sink);
        BufferedSink bufferedSink = Okio.buffer(progressSink);
        delegate.writeTo(bufferedSink);
        bufferedSink.flush();
    }

    private class ProgressSink extends ForwardingSink {

        private long bytesWritten = 0;

        public ProgressSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            if (progressListener != null) {
                bytesWritten += byteCount;
                int progressInPercentage = (int) (bytesWritten / (float) contentLength() * 100);
                if (progressInPercentage < 0 || progressInPercentage > 100) {
                    progressInPercentage = 0;
                }

                progressListener.onRequestProgress(progressInPercentage);
            }
        }
    }

    public interface ProgressListener {
        void onRequestProgress(int progressInPercentage);
    }
}
